import axiosInstance from "@/api";
import {getToken, setToken} from "@/util";

interface RequestReturn<T = any> {
    code: number
    message: string
    data: T
}

interface UseGet {
    url: string
    params: any
    success?: (data: any) => void
    fail?: (message: string, code: number) => void
    complete?: () => void
}

export async function useGet<T = any>(config: UseGet, useToken = false) {
    const token = getToken()
    const headers = useToken ? {"x-token": token} : {}
    const result = await axiosInstance.get<any, RequestReturn<T>>(config.url, {
        params: config.params, headers
    })
    if (result.code === 1000) {
        config.success && config.success(result.data)
    } else if (result.code === 1300) {
        setToken("")
        location.reload()
    } else {
        config.fail && config.fail(result.message, result.code)
    }
    config.complete && config.complete()
}

interface UsePost<T = any> {
    url: string
    data: T
    success?: (result: T) => void
    fail?: (message: string) => void
    complete?: () => void
}

export async function usePost<T = any>(config: UsePost, useToken = false) {
    const token = getToken()
    const headers = useToken ? {"x-token": token} : {}
    const result = await axiosInstance.post<any, RequestReturn<T>>(config.url, config.data, {headers: headers})
    if (result.code === 1000) {
        config.success && config.success(result.data)
    } else {
        config.fail && config.fail(result.message)
    }
    config.complete && config.complete()
}

interface UseDelete {
    url: string
    params: any
    success?: (data: any) => void
    fail?: (message: string, code: number) => void
    complete?: () => void
}

export async function useDelete<T = any>(config: UseDelete, useToken = false) {
    const token = getToken()
    const headers = useToken ? {"x-token": token} : {}
    const result = await axiosInstance.delete<any, RequestReturn<T>>(config.url, {
        params: config.params, headers
    })
    if (result.code === 1000) {
        config.success && config.success(result.data)
    } else if (result.code === 1300) {
        setToken("")
        location.reload()
    } else {
        config.fail && config.fail(result.message, result.code)
    }
    config.complete && config.complete()
}
